#!/bin/bash
# update.sh - 项目更新脚本

echo "🔄 Smart AI Chat 更新脚本"
echo "========================"

# 检查Git状态
if [ ! -d .git ]; then
    echo "❌ 当前目录不是Git仓库"
    exit 1
fi

# 备份用户数据
echo "💾 备份用户数据..."
backup_dir="backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir"
cp -r data/ "$backup_dir/" 2>/dev/null || true
cp .env "$backup_dir/" 2>/dev/null || true

# 拉取最新代码
echo "⬇️  拉取最新代码..."
git stash push -m "Auto stash before update"
git pull origin main

# 检查依赖更新
if [ requirements.txt -nt venv/pyvenv.cfg ]; then
    echo "📦 更新Python依赖..."
    source venv/bin/activate 2>/dev/null || source venv/Scripts/activate
    pip install --upgrade -r requirements.txt
fi

# 数据库迁移（如果需要）
echo "🗄️  检查数据库更新..."
if [ -f migrations/migrate.py ]; then
    python migrations/migrate.py
fi

# 恢复用户数据
echo "🔄 恢复用户数据..."
cp -r "$backup_dir/data/"* data/ 2>/dev/null || true
cp "$backup_dir/.env" . 2>/dev/null || true

echo "✅ 更新完成！"
echo "备份位置: $backup_dir"
